package bsr.basara.autodata.config;

import cn.hutool.core.util.StrUtil;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * JFinal ActiveRecordPlugin 配置
 *
 * @author basara
 */
@Configuration
@Slf4j
public class ActiveRecordConfig {

    @Bean
    public ActiveRecordPlugin initActiveRecordPlugin() {

        PropKit.use("db.properties");

        //一个数据源
        String url = PropKit.get("local.jdbcUrl");
        String user = PropKit.get("local.username");
        String password = PropKit.get("local.password");
        String driver = PropKit.get("local.driverClass");
        DruidPlugin localDb = new DruidPlugin(url, user, password, driver);
        localDb.setValidationQuery("select 1 from dual");
        localDb.start();

        // 配置ActiveRecord插件
        ActiveRecordPlugin localArp = new ActiveRecordPlugin(DbKit.MAIN_CONFIG_NAME, localDb);
        localArp.setShowSql(true);
        //配置方言
        localArp.setDialect(new MysqlDialect());
        //配置大小写不敏感
        localArp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
        localArp.start();

        //多个数据源
        if (StrUtil.isNotEmpty(PropKit.get("source.jdbcUrl"))) {
            DruidPlugin sourceDb = new DruidPlugin(PropKit.get("source.jdbcUrl"), PropKit.get("source.username"), PropKit.get("source.password"), PropKit.get("source.driverClass"));
            sourceDb.start();
            ActiveRecordPlugin sourceArp = new ActiveRecordPlugin("source", sourceDb);
            sourceArp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
            sourceArp.setShowSql(true);
            sourceArp.start();
        }
        log.info("---JFinal ActiveRecordPlugin init");
        return localArp;
    }
}
